package socializing

import (
	"github.com/gin-gonic/gin"
	"math"
	"net/http"
	"project/controller"
	"project/mySql"
)

/**
 * @File : message.go
 * @Description : 聊天功能
 * @Author : 吴概
 * @Date : 2023/2/14
 */

type ChatHistoryResponse struct {
	controller.Response
	MessageList []controller.Message `json:"message_list"`
}

var idx = 0 //用idx记录消息列表显示到哪了，避免重复输出聊天记录

func ChatHistory(c *gin.Context) {
	currentId := mySql.GetUserByToken(c.Query("token")).Id
	toUserId := controller.ParseInt(c.Query("to_user_id"))
	chat := mySql.GetChat(currentId, toUserId)
	messageList := mySql.GetMessageList(chat)
	l := int(math.Max(float64(len(messageList)-1), 0))
	mgl := messageList
	if idx > l {
		mgl = nil
	} else {
		mgl = messageList[idx:]
		idx = l
	}
	c.JSON(http.StatusOK, ChatHistoryResponse{
		Response:    controller.Response{StatusCode: 0},
		MessageList: mgl, //只返回idx到聊天记录结尾的数据
	})
	idx++
}

// ChatAction 进行发送信息操作
func ChatAction(c *gin.Context) {
	content := c.Query("content")
	currentId := mySql.GetUserByToken(c.Query("token")).Id
	toUserId := controller.ParseInt(c.Query("to_user_id"))
	chat := mySql.GetChat(currentId, toUserId)
	message := mySql.NewMessage(controller.Message{
		Content:    content,
		ToUserId:   toUserId,
		FromUserId: currentId,
	})
	chat.MessageIdList = controller.AddId(chat.MessageIdList, message.Id)
	mySql.SaveChat(chat)
	c.JSON(http.StatusOK, controller.Response{StatusCode: 0})
	idx = len(controller.GetIdList(chat.MessageIdList))
}
